<template>
  <div>
    <el-popover
      ref="popoverRef"
      v-model="visible"
      :width="260"
      placement="bottom"
      popper-class="view-filter-popover"
      trigger="click"
      @hide="cancelEdit">
      <div class="preset-filter">
        <div class="main">
          <template v-if="allViewData.length">
            <div :class="{'selected': !curView.id}" class="view-item mb4" style="width: 100%" @click="selectItem('')">默认视图</div>
            <div v-for="(item, index) in allViewData" :key="index" :class="{'selected': curView.id === item.id}" class="flex-center mb4" style="justify-content: space-between">
              <div v-if="item._isEdit" @click.stop="()=>{}">
                <el-input v-model="editName" :maxlength="50" size="small" placeholder="请输入视图名称"/>
              </div>
              <div v-else class="label-container view-item mr12" @click="selectItem(item)">
                <ToolTip :content="item.name" :tool-tip="item.name"/>
              </div>
              <div class="preset-operate">
                <div class="button-text">
                  <img :src="EditIcon" class="operate-icon" alt="" @click.stop="toEdit(item)">
                </div>
                <div class="button-text" style="margin: 0 4px 0 10px" @click="deleteItem(item)">
                  <img :src="DeleteIcon" class="operate-icon" alt="">
                </div>
              </div>
            </div>
          </template>
          <div v-else class="empty-center">
            <EmptyPlaceholder text="暂无数据" image-size="80px" empty-img-top="30px" />
          </div>
        </div>
        <div v-if="inEdit" class="operate-btn">
          <el-button class="edit-btn mobile-btn-flex" type="primary" size="small" @click="editView">
            保存
          </el-button>
          <el-button class="back-btn cancel-btn-style" type="info" size="small" @click="cancelEdit">
            取消
          </el-button>
        </div>
      </div>
      <template v-if="$slots.default">
        <slot slot="reference" />
      </template>
    </el-popover>
  </div>
</template>

<script>
import Title from '@/components/Title';
import filterIcon from '@/assets/reportManage/open-filter.png';
import deleteIcon from '@/assets/reportManage/delete-filter.png';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import EditIcon from '@/assets/config/editIcon.png';
import DeleteIcon from '@/assets/config/deleteIcon.png';
import { showModal } from '@/utils/message';
import { editViewList, deleteView } from '@/api/resource';

export default {
  name: 'PresetFilter',
  components: { Title, EmptyPlaceholder },
  props: {
    allViewData: {
      type: Array,
      default: () => []
    },
    curView: {
      type: Object | String,
      default: () => ({})
    }
  },
  data() {
    return {
      filterIcon, deleteIcon, EditIcon, DeleteIcon,
      visible: false,
      editName: ''
    };
  },
  computed: {
    inEdit() {
      return this.allViewData.some(el => !!el._isEdit);
    }
  },
  methods: {
    openEditDialog(item = null) {
      if (item && item.isFixed) return;
      this.$refs.EditPresetFilterRef.openDialog(item);
    },
    handleCloseEdit() {
      setTimeout(() => {
        this.$refs.popoverRef.doShow();
      }, 0);
    },
    getLocalView() {
      const loclView = localStorage.getItem('curView') || '{}';
      return this.jsonParse(loclView);
    },
    jsonParse(str) {
      if (typeof str !== 'string') return str;
      try {
        return JSON.parse(str);
      } catch (error) {
        console.log(error);
        return {};
      }
    },
    deleteItem({ id, platform }) {
      const loclView = this.getLocalView();
      showModal('是否删除当前视图配置').then(() => {
        deleteView(id).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功');
            if (loclView[platform] && loclView[platform].id === id) {
              delete loclView[platform];
              localStorage.setItem('curView', JSON.stringify(loclView));
            }
            if (id === this.curView.id) {
              this.$emit('changeView', '');
            }
            this.$emit('freshData');
          } else {
            this.$message.error(res.message);
          }
        });
      });
    },
    toEdit(item) {
      this.allViewData.forEach(el => {
        this.$set(el, '_isEdit', false);
      });
      this.editName = item.name;
      this.$set(item, '_isEdit', true);
    },
    editView() {
      const item = this.allViewData.find(el => !!el._isEdit);
      if (!this.editName) {
        this.$message.error('请输入视图名称');
        return;
      }
      item.name = this.editName;
      editViewList(item).then(res => {
        if (res.code === 200) {
          this.$message.success('编辑成功');
          this.$emit('freshData');
        }
      });
    },
    cancelEdit() {
      this.allViewData.forEach(el => {
        this.$set(el, '_isEdit', false);
      });
    },
    selectItem(item) {
      if (this.inEdit && item.id !== this.curView.id) {
        this.$message.warning('请先取消编辑视图后再切换');
        return;
      }
      this.$emit('changeView', item);
      this.$nextTick(() => {
        this.visible = false;
      });
    }
  }
};
</script>

<style lang="scss" scoped>
$border-color: #ddd;
$minHeight: 200px;
.setting-btn {
  cursor: pointer;
  font-size: 14px;
  font-weight: 550;
  color: #333333;
  padding: 0 5px;
  height: 28px;
  background: #edeef2;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 8px;
  img {
    width: 16px;
    height: 16px;
    margin-right: 4px;
  }
}
.preset-filter {
  .title-container {
    display: flex;
    margin-bottom: 12px;
  }
  .main {
    height: $minHeight;
    padding-right: 6px;
    @include scrollBar($x: hidden, $y: auto, $width: 6px);
  }
}

.label-container {
  display: flex;
  & ::v-deep {
    .el-tooltip.is-can-click {
      color: #666;
      &:hover {
        color: #406EFF;
      }
    }
  }
}
.default-tag {
  margin-left: 10px;
  font-size: 12px;
  color: #406EFF;
  border: 1px solid #406EFF;
  border-radius: 11px;
  flex-shrink: 0;
  width: 40px;
  height: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.edit-button {
  width: 18px;
  height: 18px;
  cursor: pointer;
  &.disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }
  img {
    width: 100%;
  }
}
.empty-center {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
.preset-operate {
  flex-shrink: 0;
  display: flex;
  align-items: center;
}
.footer-btn {
  width: 100%;
}
.view-item {
  display: flex;
  align-items: center;
  width: calc(100% - 60px);
  height: 32px;
  padding: 4px 12px;
  font-size: 14px;
  //color: #666;
  border-radius: 4px;
  cursor: pointer;
}
.operate-icon {
  width: 18px;
  height: 18px;
}
.selected {
  color: #406Eff !important;
  background: #EDEEF2;
  font-weight: 600;
  border-radius: 4px;
}
.operate-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  padding-top: 4px;
}
::v-deep {
  .el-input {
    width: 180px;
  }
}
.mb4 {
  margin-bottom: 4px;
}
</style>
<style lang="scss">
.view-filter-popover {
  border-radius: 8px !important;
  padding: 4px 4px 16px !important;
}
</style>
